package com.share.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @desc:
 * @author:caifan
 * @date:2022/4/2
 */
public class CyclicBarrierDemo01 {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
            System.out.println("开始做核算了=======");
        });
        for (int i = 1; i <= 20; i++) {
            new Thread(new Task(i, cyclicBarrier)).start();
        }
    }


    static class Task implements Runnable {
        private int i;
        private CyclicBarrier cyclicBarrier;

        public Task(int i, CyclicBarrier cyclicBarrier) {
            this.i = i;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                System.out.println("人员" + i + "排队等待做核算");
                cyclicBarrier.await();
                System.out.println("医护人员给" + i + "做核算");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

}
